import type { Module } from 'vuex'
import type { ILoginState } from './types'
import type { IRootState } from '../types'
import { ElMessageBox } from 'element-plus'
import sysCache from '@/utils/cache'
import router from '@/router'
import { accountLoginRequest, requestUserInfoById, requestUserMenus } from '@/service/user/user'
import { IAccount } from '@/service/user/type'
import { ElMessage } from 'element-plus'

const login: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      // 用户的角色列表
      roleList: [],
      // 是否动态添加路由
      isDynamicAddedRoute: false
    }
  },
  getters: {},
  mutations: {
    setToken(state, token: string) {
      state.token = token
      sysCache.localCache.setCache('token', token)
    },
    setUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
      sysCache.localCache.setCache('userInfo', userInfo)
    },
    setRoleList(state, roleList: string[]) {
      state.roleList = roleList
      sysCache.localCache.setCache('roleList', roleList)
    },
    setDynamicAddedRoute(state, added: boolean) {
      state.isDynamicAddedRoute = added
    }
  },
  actions: {
    confirmLoginOut: async ({ commit }) => {
      try {
        const res = await ElMessageBox.confirm('是否确认退出系统?', '温馨提醒', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
        if (res) {
          sysCache.localCache.removeCache('token')
          commit('setDynamicAddedRoute', false)
          router.push({
            path: '/login'
          })
        }
      } catch (e) {
        console.log(e)
      }
    },
    async accountLoginAction({ commit, dispatch, state }, payload: IAccount) {
      // 1.实现登录逻辑
      const loginResult = await accountLoginRequest(payload)
      const { token, id } = loginResult.data
      // 保存token
      commit('setToken', token)

      // 2.获取用户信息
      await dispatch('getUserInfoAction', id)

      // 3.动态添加路由
      if (!state.isDynamicAddedRoute) {
        const routes = await dispatch('buildRoutesAction', null, { root: true })
        routes.forEach((route) => {
          router.addRoute('Layout', route)
        })
        commit('setDynamicAddedRoute', true)
      }

      ElMessage({
        message: '登录成功',
        type: 'success'
      })
      // 4.跳到首页
      router.replace('/')
    },
    async getUserInfoAction({ commit }, userId: string) {
      // 2.请求用户信息
      const userInfoResult = await requestUserInfoById(userId)
      const userInfo = userInfoResult.data
      commit('setUserInfo', userInfo)

      // 获取用户的角色列表
      const roleList = userInfo.roles.map((item) => item.value)
      commit('setRoleList', roleList)
    },
    // 后台动态获取菜单模式下，才需要获取菜单
    async getUserMenus() {
      // 请求用户菜单
      const userMenusResult = await requestUserMenus()
      const userMenus = userMenusResult.data
      return userMenus
    },
    // 加载本地用户信息，解决页面刷新，store数据丢失
    loadLocalLogin({ commit }) {
      const token = sysCache.localCache.getCache('token')
      if (token) {
        commit('setToken', token)
      }
      const userInfo = sysCache.localCache.getCache('userInfo')
      if (userInfo) {
        commit('setUserInfo', userInfo)
      }
      const roleList = sysCache.localCache.getCache('roleList')
      if (roleList) {
        commit('setRoleList', roleList)
      }
      const menuList = sysCache.localCache.getCache('menuList')
      if (menuList) {
        commit('setMenuList', menuList, { root: true })
      }
    }
  }
}

export default login
